<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        .content-container {
            padding-top: 60px;
            padding-bottom: 100px;
        }
        .message-row {
            display: flex;
            margin-bottom: 8px;
            align-items: stretch;
            min-height: 40px;
        }
        .character-name {
            width: 120px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-right: 4px;
            text-align: center;
            background-color: #FFCCCC;
            font-size: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            word-break: break-word;
        }
        .message-content {
            flex: 1;
            overflow-wrap: break-word;
            white-space: pre-wrap;
            min-height: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            color: #000000;
            text-align: left;
            font-size: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px #ccc;
            display: flex;
            align-items: center;
            /* 新增醒目光标样式 */
            caret-color: #ff0000; /* 红色光标 */
            cursor: text;
        }
        .message-content:focus {
            outline: none;
            border-color: #0066cc;
            /* 聚焦时更醒目的光标 */
            caret-color: #ff0000;
            text-shadow: 0 0 3px rgba(255,0,0,0.5);
        }
    </style>
    <!-- 修改为绝对路径引入QWebChannel -->
    <script>
    // 动态加载QWebChannel.js
    function loadQWebChannel(callback) {
        if (typeof QWebChannel !== 'undefined') {
            callback(true);
            return;
        }

        const script = document.createElement('script');
        script.src = 'qrc:///qtwebchannel/qwebchannel.js';
        script.onload = () => callback(true);
        script.onerror = () => {
            console.error('Failed to load QWebChannel.js');
            callback(false);
        };
        document.head.appendChild(script);
    }

    // 初始化流程
    function initApp() {
        loadQWebChannel((success) => {
            if (!success) {
                console.error('QWebChannel.js加载失败，请检查路径');
                return;
            }

            if (typeof qt === 'undefined' || !qt.webChannelTransport) {
                console.error('Qt环境未就绪');
                return;
            }

            try {
                new QWebChannel(qt.webChannelTransport, function(channel) {
                    window.pyObject = channel.objects.pyObject;
                    console.log('WebChannel初始化成功');
                });
            } catch (e) {
                console.error('初始化失败:', e);
            }
        });
    }

    // 启动初始化
    document.addEventListener('DOMContentLoaded', initApp);
    </script>
    <script>
        // 全局变量，用于调试
        let debugInfo = {
            lastEvent: null,
            lastSelection: null,
            lastError: null
        };

        // 确保logger对象存在
        const logger = window.logger || {
            debug: (...args) => console.debug('[DEBUG]', ...args),
            info: (...args) => console.info('[INFO]', ...args),
            warn: (...args) => console.warn('[WARN]', ...args),
            error: (...args) => console.error('[ERROR]', ...args)
        };

        function logDebug(type, info) {
            logger.debug(`[DEBUG] ${type}:`, info);
            debugInfo[`last${type}`] = info;
        }

        function initializeContentEditable(element) {
            element.contentEditable = true;
            element.addEventListener('input', () => handleContentChange(element));
            element.addEventListener('keydown', async function(e) {
                try {
                    logDebug('Event', {
                        key: e.key,
                        shiftKey: e.shiftKey,
                        target: e.target.tagName
                    });

                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        // 处理回车键
                        const selection = window.getSelection();
                        if (!selection.rangeCount) {
                            console.log("没有选择范围");
                            return;
                        }

                        const range = selection.getRangeAt(0);
                        const currentContent = range.startContainer;
                        const currentDiv = currentContent.nodeType === Node.TEXT_NODE ?
                            currentContent.parentElement : currentContent;

                        if (!currentDiv || !currentDiv.classList.contains('message-content')) {
                            console.log("不在消息内容区域内");
                            return;
                        }

                        const text = currentDiv.textContent;
                        const position = range.startOffset;
                        const positionInfo = JSON.stringify({
                            text: text,
                            position: position,
                            beforeText: text.substring(0, position),
                            afterText: text.substring(position),
                            id: currentDiv.parentElement.getAttribute('id')
                        });

                        // 使用Promise包装QWebChannel调用
                        new Promise((resolve) => {
                            new QWebChannel(qt.webChannelTransport, function(channel) {
                                channel.objects.handler.handleEnterKey(positionInfo, resolve);
                            });
                        }).then(() => {
                            const newRowId = parseInt(currentDiv.parentElement.getAttribute('id')) + 1;
                            restoreCursorPosition(newRowId.toString(), 0);
                        });
                    } else if (e.key === 'Backspace') {
                        const selection = window.getSelection();
                        if (!selection.rangeCount) return;

                        const range = selection.getRangeAt(0);
                        const startContainer = range.startContainer;
                        if (!startContainer) return;

                        // 确保currentDiv正确定义
                        const currentDiv = startContainer.nodeType === Node.TEXT_NODE ?
                            startContainer.parentElement.closest('.message-content') :
                            startContainer.closest('.message-content');

                        if (!currentDiv) return;
                        const text = currentDiv.textContent;

                        // 检查是否在行首
                        if (range.startOffset === 0) {
                            // 检查是否真的在行首（考虑到可能有多个文本节点）
                            let isAtStart = true;
                            if (startContainer.nodeType === Node.TEXT_NODE) {
                                // 检查是否有前面的兄弟节点
                                let node = startContainer.previousSibling;
                                while (node) {
                                    if (node.nodeType === Node.TEXT_NODE && node.textContent.trim().length > 0) {
                                        isAtStart = false;
                                        break;
                                    }
                                    node = node.previousSibling;
                                }
                            }

                            if (isAtStart) {
                                const messageRow = currentDiv.parentElement;
                                const prevRow = messageRow.previousElementSibling;
                                if (prevRow) {
                                    e.preventDefault();
                                    const position = range.startOffset;
                                    const prevContent = prevRow.querySelector('.message-content');

                                    // 保存当前光标位置
                                    const currentPosition = range.startOffset;

                                    const positionInfo = JSON.stringify({
                                        text: text,
                                        position: position,
                                        beforeText: text.substring(0, position),
                                        afterText: text.substring(position),
                                        id: messageRow.getAttribute('id'),
                                        prevId: prevRow.getAttribute('id'),
                                        currentPosition: currentPosition
                                    });

                                    // 使用Promise包装QWebChannel调用
                                    new Promise((resolve) => {
                                        new QWebChannel(qt.webChannelTransport, function(channel) {
                                            channel.objects.handler.handleBackspaceKey(positionInfo, resolve);
                                        });
                                    }).then(() => {
                                        if (prevContent) {
                                            const mergedText = prevContent.textContent;
                                            const newPosition = Math.max(0, mergedText.length - currentPosition);
                                            restoreCursorPosition(prevRow.getAttribute('id'), newPosition);
                                        }
                                    });
                                }
                            }
                        }
                    }
                } catch (error) {
                    console.error("键盘事件处理错误:", error);
                    logDebug('Error', error.toString());
                }
            });
        }

        function handleContentChange(element) {
            try {
                // 获取所有消息内容
                let messages = [];
                document.querySelectorAll('.message-row').forEach(row => {
                    const nameElement = row.querySelector('.character-name');
                    const contentElement = row.querySelector('.message-content');

                    // 获取背景颜色，如果没有设置则默认为白色
                    const color = nameElement.style.backgroundColor || 'white';

                    messages.push({
                        name: nameElement.textContent.trim(),
                        defaultText: contentElement.textContent.trim(),
                        color: color
                    });
                });
                // 通知Python端内容已更改
                new QWebChannel(qt.webChannelTransport, function(channel) {
                    channel.objects.handler.contentChanged(JSON.stringify(messages));
                });

                // 调整行高度
                setTimeout(adjustRowHeights, 0);
            } catch (error) {
                console.error("内容变化处理错误:", error);
                logDebug('Error', error.toString());
            }
        }

        // 调整行高度，确保角色名称和内容高度一致
        function adjustRowHeights() {
            try {
                document.querySelectorAll('.message-row').forEach(row => {
                    const nameElement = row.querySelector('.character-name');
                    const contentElement = row.querySelector('.message-content');

                    if (!nameElement || !contentElement) return;

                    // 重置高度以获取自然高度
                    nameElement.style.height = 'auto';
                    contentElement.style.height = 'auto';

                    // 获取两者的自然高度
                    const nameHeight = nameElement.offsetHeight;
                    const contentHeight = contentElement.offsetHeight;

                    // 使用较大的高度
                    const maxHeight = Math.max(nameHeight, contentHeight);
                    nameElement.style.minHeight = maxHeight + 'px';
                    contentElement.style.minHeight = maxHeight + 'px';
                });
            } catch (error) {
                console.error("调整行高度错误:", error);
            }
        }

        // 初始化所有内容元素
        function initializeAllContents() {
            try {
                document.querySelectorAll('.message-content').forEach(content => {
                    initializeContentEditable(content);
                });

                // 初始化角色名称元素的可编辑性
                document.querySelectorAll('.character-name').forEach(name => {
                    name.contentEditable = true;
                    name.addEventListener('input', () => {
                        handleContentChange(null);
                        // 调整高度
                        setTimeout(adjustRowHeights, 0);
                    });
                });

                // 调整初始高度
                setTimeout(adjustRowHeights, 0);
            } catch (error) {
                console.error("初始化内容错误:", error);
            }
        }

        // 观察DOM变化，为新添加的内容元素初始化可编辑性
        const observer = new MutationObserver(mutations => {
            let needsHeightAdjustment = false;

            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) { // 元素节点
                        const contents = node.classList.contains('message-content') ?
                            [node] :
                            node.querySelectorAll('.message-content');
                        contents.forEach(content => {
                            initializeContentEditable(content);
                        });

                        // 初始化角色名称元素
                        const names = node.classList.contains('character-name') ?
                            [node] :
                            node.querySelectorAll('.character-name');
                        names.forEach(name => {
                            name.contentEditable = true;
                            name.addEventListener('input', () => {
                                handleContentChange(null);
                                setTimeout(adjustRowHeights, 0);
                            });
                        });

                        needsHeightAdjustment = true;
                    }
                });
            });

            // 如果有新元素添加，调整高度
            if (needsHeightAdjustment) {
                setTimeout(adjustRowHeights, 0);
            }
        });

        document.addEventListener('DOMContentLoaded', function() {
            // 初始化现有内容
            initializeAllContents();

            // 开始观察DOM变化
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });

            // 如果没有内容，添加一个空行
            if (document.querySelectorAll('.message-row').length === 0) {
                const container = document.querySelector('.content-container');
                const emptyRow = document.createElement('div');
                emptyRow.className = 'message-row';
                emptyRow.innerHTML = `
                    <div class="character-name" contenteditable="true" style="background-color: white">旁白</div>
                    <div class="message-content" style="background-color: white"></div>
                `;
                container.appendChild(emptyRow);
                initializeAllContents();
            }

            // 确保QWebChannel已加载
            if (typeof Qt === 'undefined' || typeof QWebChannel === 'undefined') {
                console.error('Error: Qt or QWebChannel not loaded');
                return;
            }

            // 初始化QWebChannel
            new QWebChannel(qt.webChannelTransport, function(channel) {
                window.pyObject = channel.objects.pyObject;
            });
        });

        // 增强版QWebChannel初始化
        function initWebChannel() {
            // 检查资源是否加载
            if (typeof QWebChannel === 'undefined') {
                console.error('QWebChannel.js not loaded, retrying...');
                setTimeout(initWebChannel, 500);
                return;
            }

            // 检查Qt环境
            if (typeof qt === 'undefined' || !qt.webChannelTransport) {
                console.error('Qt环境未就绪');
                return;
            }

            // 初始化QWebChannel
            try {
                new QWebChannel(qt.webChannelTransport, function(channel) {
                    window.pyObject = channel.objects.pyObject;
                    console.log('WebChannel初始化成功');
                });
            } catch (e) {
                console.error('WebChannel初始化失败:', e);
                setTimeout(initWebChannel, 1000);
            }
        }

        // 启动初始化流程
        setTimeout(initWebChannel, 0);

        // 增强版光标恢复函数
        function restoreCursorPosition(rowId, position) {
            console.log(`尝试恢复光标到行${rowId}位置${position}`);

            // 第一次尝试（500ms延迟确保DOM更新）
            setTimeout(() => {
                try {
                    const row = document.querySelector(`.message-row[id="${rowId}"]`);
                    if (!row) {
                        console.error(`找不到行: ${rowId}`);
                        return;
                    }

                    const content = row.querySelector('.message-content');
                    if (!content) {
                        console.error(`找不到内容区域: ${rowId}`);
                        return;
                    }

                    // 确保元素可见
                    content.scrollIntoView({ behavior: 'auto', block: 'nearest' });

                    // 设置选择范围
                    const range = document.createRange();
                    const textNode = content.firstChild || content;
                    const maxPosition = textNode.length || 0;
                    const safePosition = Math.min(position, maxPosition);

                    range.setStart(textNode, safePosition);
                    range.collapse(true);

                    const selection = window.getSelection();
                    selection.removeAllRanges();
                    selection.addRange(range);

                    // 强制设置焦点（300ms延迟）
                    setTimeout(() => {
                        content.focus();
                        console.log('第一次焦点设置完成');

                        // 二次确认（200ms后）
                        setTimeout(() => {
                            if (document.activeElement !== content) {
                                console.warn('焦点设置失败，执行强制聚焦');
                                content.focus({ preventScroll: true });

                                // 第三次确认（100ms后）
                                setTimeout(() => {
                                    if (document.activeElement !== content) {
                                        console.error('最终焦点设置失败');
                                    } else {
                                        console.log('焦点设置成功');
                                    }
                                }, 100);
                            }
                        }, 200);
                    }, 300);
                } catch (error) {
                    console.error('光标恢复错误:', error);
                }
            }, 500); // 初始延迟
        }
    </script>
</head>
<body>
    <div class="content-container">
        {{content_rows}}
    </div>
</body>
</html>
